package com.common.util.util;
import com.common.bean.BaseEntity;
import com.common.bean.Entity;
import com.common.exception.ParameterException;
import lombok.NonNull;
import org.apache.commons.lang3.StringUtils;

import java.time.LocalDateTime;

/**
 * @author pengzhen
 * @email pengzhen
 * @date 2019/3/22 10:35 2019 03
 */

public final class BaseEntityUtils   {
  enum   StatusEnum {

    /**
     * 已删除
     */
    DELETE(new Byte("-1")),

    /**
     * * 草稿
     */
    UNDEFINED(new Byte("0")),

    /**
     * 审核中
     */
    UNDER_REVIEW(new Byte("1")),

    /**
     * 2 正常
     */
    NORMAL(new Byte("2")),

    /**
     * 3 审核未通过
     */
    AUDIT_FAILED(new Byte("3")),
    ;


    StatusEnum(byte status) {
      this.status = status;
    }

    private byte  status;

    public final static   boolean  isSuccess(byte status){
      for (StatusEnum value : StatusEnum.values()) {
        if( value.status==status){
          return  false;
        }
      }
      return  true;
    }


  }

 public enum   ExpireEnum {

    /**
     * 已过期
     */
    DELETE(new Byte("-1")),

    /**
     * * 草稿
     */
    UNDEFINED(new Byte("0")),

    /**
     * 正常
     */
    UNDER_REVIEW(new Byte("1")),

    /**
     * 2 快过期
     */
    NORMAL(new Byte("2")),

    ;


    ExpireEnum(byte status) {
      this.status = status;
    }

    private byte  status;

    public final static   boolean  isSuccess(byte status){
      for (ExpireEnum value : ExpireEnum.values()) {
        if( value.status==status){
          return  false;
        }
      }
      return  true;
    }

   public byte getStatus() {
     return status;
   }
 }

  public static void  query(@NonNull BaseEntity baseEntity){
    baseEntity.setStatus(StatusEnum.NORMAL.status);
  }

  public static byte  check(@NonNull Byte baseEntity){
      return  StatusEnum.isSuccess(baseEntity)?baseEntity: StatusEnum.NORMAL.status;
  }


  /**
   * 设置：update
   */
  public static void update(@NonNull Entity baseEntity) {
    baseEntity.setGmtCreate(null);
    baseEntity.setGmtModified(LocalDateTime.now());
    handleRemark(baseEntity);
    if(baseEntity.getId()==null){throw  new ParameterException(" id   is   null"); }
    handleStatus(baseEntity);

  }

  /**
   * 获取：insert
   */
  public static void insert(@NonNull Entity baseEntity) {
    baseEntity.setGmtCreate(LocalDateTime.now());
    baseEntity.setGmtModified(LocalDateTime.now());
    handleRemark(baseEntity);
    baseEntity.setId(null);
    baseEntity.setStatus(StatusEnum.NORMAL.status);

  }



  private static void handleRemark(@NonNull BaseEntity baseEntity) {
    if(StringUtils.isBlank(baseEntity.getRemarks())){
      baseEntity.setRemarks("");
    }
  }

  private static void handleStatus(@NonNull BaseEntity baseEntity) {
    if(StatusEnum.isSuccess(baseEntity.getStatus())){
      throw  new ParameterException("status  is  error  ,Illegal parameter ");
    }
  }
}
